package com.sharding.transaction.demo.consumer;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sharding.transaction.demo.api.IAccountProviderService;
import com.sharding.transaction.demo.api.IOrderProviderService;
import com.sharding.transaction.demo.api.IStoreProviderService;
import com.sharding.transaction.demo.entity.CommonDict;
import com.sharding.transaction.demo.entity.Goods;
import com.sharding.transaction.demo.entity.Orders;
import com.sharding.transaction.demo.entity.User;
import com.sharding.transaction.demo.mapper.CommonDictMapper;
import com.sharding.transaction.demo.vo.OrdersVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BussinessProviderService {

    @Reference(version = "1.0.0", group = "sharding-tr", timeout = 30000)
    private IOrderProviderService orderProviderService;

    @Reference(version = "1.0.0", group = "sharding-tr")
    private IAccountProviderService accountProviderService;

    @Reference(version = "1.0.0", group = "sharding-tr")
    private IStoreProviderService storeProviderService;

    @Autowired
    private CommonDictMapper commonDictMapper;

//    AT
    @GlobalTransactional
    public Orders takeOrder(Long userId, Long goodsId, Integer store){
        List<CommonDict> commonDicts = commonDictMapper.selectList(null);
        System.out.println("commonDicts=====:" + commonDicts.size());
        Goods goods = storeProviderService.getById(goodsId);
        Orders orders = orderProviderService.takeOrderSuc(userId, goodsId, store);
        if(orders != null){
            User user = accountProviderService.deductionAccountSuc(userId, Double.valueOf(goods.getPrice() * store));
            if(user != null){
                return orders;
            }
        }
        throw new RuntimeException("bussiness consumer -:下单失败！！！！");
    }


    public IPage<Orders> orders(Integer pageSize, Integer pageNumber, OrdersVo orders) {
        return orderProviderService.orders(pageSize, pageNumber, orders);
    }
}
